﻿using System;
using MongoDB.Driver;
using Sustainalytics.Entities;

namespace Sustainalytics.DataLayer
{
    /// <summary>
    /// Notification repository
    /// </summary>
    public class NotificationsRepository : INotificationsRepository
    {
        private MongoClient Client { get; set; }
        private IMongoDatabase Database { get; set; }

        private NotificationsRepository(string connectionString)
        {
            MongoUrl mongoUrl = MongoUrl.Create(connectionString);

            if (string.IsNullOrWhiteSpace(mongoUrl.DatabaseName)) throw new ArgumentException("No database specified in the connection string!");

            // Mongo DB client
            Client = new MongoClient(mongoUrl);

            // Mongo DB
            Database = Client.GetDatabase(mongoUrl.DatabaseName);
        }

        public static INotificationsRepository GetNotificationRepository(string connectionString)
        {
            return new NotificationsRepository(connectionString);            
        }

        public Notifications GetNotification()
        {
            return Database.GetCollection<Notifications>("Notifications").Find(_ => true).SingleOrDefault() ??
                new Notifications
                {
                    Id = Guid.NewGuid(),
                    Status = NotificationsStatus.Unpublished,
                    Body = string.Empty
                };
        }

        public void UpsertNotification(Notifications notification)
        {
            //new item
            if (notification.Id == Guid.Empty)
            {
                notification.Id = Guid.NewGuid();
                Database.GetCollection<Notifications>("Notifications").InsertOne(notification);
                return;
            }

            Database.GetCollection<Notifications>("Notifications").FindOneAndReplace(x=> x.Id == notification.Id, notification);
        }
    }
}
